route.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { listMonths } from "@/lib/storage";
  2. import { getSession } from "@/lib/auth/session";
  3. import { canAccessBranch } from "@/lib/auth/permissions";
  4. import {
  5. withErrorHandling,
  6. json,
  7. badRequest,
  8. unauthorized,
  9. forbidden,
  10. } from "@/lib/api/errors";
  11. import { mapStorageReadError } from "@/lib/api/storageErrors";
  12. /**
  13. * GET /api/branches/[branch]/[year]/months
  14. *
  15. * Happy-path response must remain unchanged:
  16. * { "branch": "NL01", "year": "2024", "months": ["10", ...] }
  17. */
  18. export const GET = withErrorHandling(
  19. async function GET(request, ctx) {
  20. const session = await getSession();
  21. if (!session) {
  22. throw unauthorized("AUTH_UNAUTHENTICATED", "Unauthorized");
  23. }
  24. const { branch, year } = await ctx.params;
  25. // Validate required route params early.
  26. const missing = [];
  27. if (!branch) missing.push("branch");
  28. if (!year) missing.push("year");
  29. if (missing.length > 0) {
  30. throw badRequest(
  31. "VALIDATION_MISSING_PARAM",
  32. "Missing required route parameter(s)",
  33. { params: missing }
  34. );
  35. }
  36. if (!canAccessBranch(session, branch)) {
  37. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  38. }
  39. try {
  40. const months = await listMonths(branch, year);
  41. return json({ branch, year, months }, 200);
  42. } catch (err) {
  43. throw await mapStorageReadError(err, { details: { branch, year } });
  44. }
  45. },
  46. { logPrefix: "[api/branches/[branch]/[year]/months]" }
  47. );